﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QFile>
#include <QTimer>
#include <QMouseEvent>
#include <QTextBlock>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    timer1s = new QTimer(this);
    timer1s->setInterval(300);

    connect(timer1s, &QTimer::timeout, this, [=]()
    {
        if(cursorPos == lineCount)
            return;
        cursorPos++;
        ui->textBrowser->setStep(cursorPos);
    });
    connect(ui->textBrowser, &CodeBrowser::stepChanged, [this](int step) {cursorPos = step;});

    ui->textEdit->setReadOnly(true);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if(event->button() == Qt::RightButton)
    {
        QMenu *pm =  ui->textBrowser->createStandardContextMenu(event->pos());
        pm->exec();
    }
}


void MainWindow::on_btn_open_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, "打开文档");
    if(fileName.isEmpty())
        return;
    QFile f(fileName);
    f.open(QFile::ReadOnly);
    QString s = f.readAll();
    ui->plainTextEdit->setPlainText(s);
    ui->textEdit->setText(s);
    ui->textBrowser->setCode(s);
    lineCount = ui->textBrowser->stepCount();
    if(timer1s->isActive())
        timer1s->stop();
    timer1s->start();
}


void MainWindow::on_btn_clear_clicked()
{
    if(timer1s->isActive())
        timer1s->stop();
    ui->textBrowser->clear();
    ui->textEdit->clear();
    ui->plainTextEdit->clear();
}

